﻿using AduSkin.Controls.Metro;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using Image = System.Windows.Controls.Image;

namespace chat_winform_wpf
{
    // ListBox 样式
    // https://blog.csdn.net/tieshuxianrezhang/article/details/79274143
    // https://blog.csdn.net/weixin_33755847/article/details/93446276?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-1&spm=1001.2101.3001.4242
    /// <summary>
    /// chatRoom.xaml 的交互逻辑
    /// </summary>
    public partial class chatRoom : UserControl
    {
        public List<UserInfo> UserList { get; set; }
        public List<ChatMessageRow> _messageList = new List<ChatMessageRow>();

        public chatRoom()
        {
            InitializeComponent();

          //  Resources["MyDataTemplateSelector"] = new MessageDataTemplateSelector(this);

            init();
        }

        public void init()
        {
            string aa = AppDomain.CurrentDomain.BaseDirectory;

            BitmapImage bi = new BitmapImage();
            // BitmapImage.UriSource must be in a BeginInit/EndInit block.
            bi.BeginInit();
            bi.UriSource = new Uri(aa + @"/Img/Header/头像6.png", UriKind.RelativeOrAbsolute);
            bi.EndInit();
            // Set the image source.
            imageStaff.Source = bi;


            ObservableCollection<PersonNP1> ocP = new ObservableCollection<PersonNP1>() {
            new PersonNP1(){Image = aa + @"/Img/Header/头像1.png", Text="十步杀一人"},
            new PersonNP1(){Image = aa + @"/Img/Header/头像3.png", Text="千里不留行"},
            };

            //listBx.ItemsSource = ocP;  
            UserList = new List<UserInfo>()
            {
                new UserInfo(){
                    Image=aa + @"/Img/Header/头像1.png",
                    Name="DESKTOP-0N",
                    Info="我要像风一样自由!",
                    Count=99
                },
                new UserInfo(){
                    Image=aa + @"/Img/Header/头像2.png",
                    Name="张三丰",
                    Info="我要像风一样自由!",
                    Count=99
                },
                new UserInfo(){
                    Image=aa + @"/Img/Header/头像3.png",
                    Name="我要像风一样自由我要像",
                    Info="我要像风一样自由!",
                    Count=99
                }
            };
            this.UserInfoList.ItemsSource = UserList;

            List<Text> messageList = new List<Text>();
            Text tt = new Text();
            tt.SenderID = 1;
            tt.MessageWidth = "300";
            tt.TalkID = aa + @"/Img/Header/头像3.png";
            tt.MessageType = NIMMessageType.kNIMMessageTypeText;
            List<ChatMessageRow> msgList = new List<ChatMessageRow>() {
                new ChatMessageRow(){
                    rowType = "Paragraph",
                    rowMessaget = new List<ChatMessage>(){
                        new ChatMessage(){
                            messageType = 0,
                            text = "提剑跨骑挥鬼雨，白骨如山鸟惊飞"
                        }
                    }
                },
                new ChatMessageRow(){
                    rowType = "Paragraph",
                    rowMessaget = new List<ChatMessage>(){
                        new ChatMessage(){
                            messageType = 0,
                            text = "生下来吧，我和他姓；她的孩子你不配样"
                        }
                    }
                }

            };

            tt.TextContent = JsonConvert.SerializeObject(msgList);
            messageList.Add(tt);

            tt = new Text();
            tt.MessageWidth = "300";
            tt.SenderID = 1;
            tt.TalkID = aa + @"/Img/Header/头像5.png";
            tt.MessageType = NIMMessageType.kNIMMessageTypeText;
            msgList = new List<ChatMessageRow>() {
                 new ChatMessageRow(){
                    rowType = "Paragraph",
                    rowMessaget = new List<ChatMessage>(){
                        new ChatMessage(){
                            messageType = 0,
                            text = "那一天黄昏，夕阳最后的余晖也映不出你的容貌，渐去渐远的背影，逐渐放大我的身影，我知道这是我们认识的最后一场雨。"
                        }
                    }
                }

               
            };
            tt.TextContent = JsonConvert.SerializeObject(msgList);
            messageList.Add(tt);

            tt = new Text();
            tt.MessageWidth = "200";
            tt.SenderID = 0;
            tt.TalkID = aa + @"/Img/Header/头像6.png";
            tt.MessageType = NIMMessageType.kNIMMessageTypeText;
            msgList = null;
            msgList = new List<ChatMessageRow>() {
               new ChatMessageRow(){
                    rowType = "Paragraph",
                    rowMessaget = new List<ChatMessage>(){
                        new ChatMessage(){
                            messageType = 0,
                            text = "红尘不在"
                        }
                    }
                }
            };
            tt.TextContent = JsonConvert.SerializeObject(msgList);
            messageList.Add(tt);


            this.MessageInfoList.ItemsSource = messageList;
        }

        private void Button_Click_Send(object sender, RoutedEventArgs e)
        {
            /* string strTemp1, strTemp2, strTemp3, strTemp4;
             XmlNode nodeTemp;

             string strXaml = XamlWriter.Save(richText_Send.Document);
             XmlDocument doc = new XmlDocument();
             doc.LoadXml(strXaml);
             //XmlNode xn = doc.SelectSingleNode("bookste");
             XmlNode xn = doc.ChildNodes[0];
             XmlNodeList xnList = xn.ChildNodes;
             Dictionary<string, string> dictinoary = new Dictionary<string, string>();
             foreach (XmlNode xnode in xnList)
             {
                 List<ChatMessage> cmList = new List<ChatMessage>();
                 if (xnode.Name == "Paragraph")
                 {
                     foreach(XmlNode xnodePra in xnode.ChildNodes)
                     {
                         if(xnodePra.Name == "Run")
                         {
                             cmList.Add(new ChatMessage {
                                 messageType = 0,
                                 text = xnode.Value.ToString()
                             });
                         }
                         else if(xnodePra.Name == "Image")
                         {
                             nodeTemp = xnodePra.FirstChild["BitmapImage"];
                             strTemp1 = nodeTemp.Attributes["UriSource"].Value.ToString();

                             cmList.Add(new ChatMessage
                             {
                                 messageType = 0,
                                 text = xnode.Value.ToString(),
                                 param1 = xnodePra.Attributes["Width"].Value.ToString(),
                                 param2 = xnodePra.Attributes["Height"].Value.ToString()

                             });
                         }
                     }

                     _messageList.Add(cmList);
                 }
                 else if(xnode.Name == "BlockUIContainer")
                 {

                 }

             }*/

            string strXaml = XamlWriter.Save(richText_Send.Document);
            _messageList.Clear();
            FlowDocument  doc = richText_Send.Document;
            for(int i = 0;i < doc.Blocks.Count; ++i)
            {
                ChatMessageRow cmList = new ChatMessageRow();

                Type type = doc.Blocks.ElementAt(i).GetType();
                if(type.Name.Equals("Paragraph"))
                {
                    cmList.rowType = "Paragraph";
                    cmList.rowMessaget = new List<ChatMessage>();

                    Paragraph pgh = (doc.Blocks.ElementAt(i) as Paragraph);
                    for (int ip = 0; ip < pgh.Inlines.Count; ++ip)
                    {
                        type = pgh.Inlines.ElementAt(ip).GetType();  
                        if(type.Name.Equals("Run"))
                        {
                            Run run = pgh.Inlines.ElementAt(ip) as Run;
                            cmList.rowMessaget.Add(new ChatMessage
                            {
                                messageType = 0,
                                text = run.Text.ToString()
                            });
                        }
                        else if(type.Name.Equals("InlineUIContainer"))
                        {
                            InlineUIContainer inl = pgh.Inlines.ElementAt(ip) as InlineUIContainer;
                            type = inl.Child.GetType();
                            if(type.Name.Equals("Image"))
                            {
                                Image img = inl.Child as Image;

                                string fileName = DateTime.Now.ToString("yyyMMddhhmmssfff") + (new Random()).Next(1000, 9999).ToString() + ".png";
                                fileName = @"F:\test\test\" + fileName;
                                saveImageToStore(fileName, img);

                                cmList.rowMessaget.Add(new ChatMessage
                                {
                                    messageType = 1,
                                    text = fileName,
                                    param1 = img.ActualWidth.ToString(),
                                    param2 = img.ActualHeight.ToString()
                                });
                            }

                        }
                    }
                }
                else if(type.Name.Equals("BlockUIContainer"))
                {
                    cmList.rowType = "BlockUIContainer";
                    cmList.rowMessaget = new List<ChatMessage>();

                    BlockUIContainer bui = (doc.Blocks.ElementAt(i) as BlockUIContainer);
                    type = bui.Child.GetType();
                    if (type.Name.Equals("Image"))
                    {
                        Image img = bui.Child as Image;

                        string fileName = DateTime.Now.ToString("yyyMMddhhmmssfff") + (new Random()).Next(1000, 9999).ToString() + ".png";
                        fileName = @"F:\test\test\" + fileName;
                        saveImageToStore(fileName, img);

                        cmList.rowMessaget.Add(new ChatMessage
                        {
                            messageType = 1,
                            text = fileName,
                            param1 = img.Width.ToString(),
                            param2 = img.Height.ToString()
                        });
                    }
                }

                _messageList.Add(cmList);
            }
            receiveData();

        }

       
        private void saveImageToStore(string url, System.Windows.Controls.Image img)
        {
            System.Windows.Media.Imaging.BitmapSource transformedBitmapSource = img.Source as BitmapSource;
            var pngBitmapEncoder = new PngBitmapEncoder();
            var stream = new FileStream(url, FileMode.Create);

            var scale = new ScaleTransform(1, 1);
            var tb = new TransformedBitmap(transformedBitmapSource, scale);
            pngBitmapEncoder.Frames.Add(BitmapFrame.Create(tb));
            pngBitmapEncoder.Save(stream);
            stream.Close();
        }


        private void receiveData()
        {
            /*List<Text> messageList = this.MessageInfoList.ItemsSource as List<Text>;
            if (messageList != null)
            {
                Text tt = new Text();
                tt.MessageWidth = "200";
                tt.SenderID = 0;
                tt.TalkID = AppDomain.CurrentDomain.BaseDirectory + @"/Img/Header/头像6.png";
                tt.MessageType = NIMMessageType.kNIMMessageTypeText;
                List<EmoticonText> etList = new List<EmoticonText>() {
                    new EmoticonText()
                    {
                        Key = "text",
                       // Value = tr.Text
                    }
                 };
                tt.TextContent = JsonConvert.SerializeObject(etList);
                messageList.Add(tt);


                //                 MessageInfoList.Dispatcher.Invoke(
                //                     new Action(() => { this.MessageInfoList.ItemsSource = messageList; }),
                //                 null);

                MessageInfoList.Items.Refresh();
                MessageInfoList.ScrollIntoView(MessageInfoList.Items[MessageInfoList.Items.Count - 1]);           
                richText_Send.Document.Blocks.Clear();//清空
            }*/

            List<Text> messageList = this.MessageInfoList.ItemsSource as List<Text>;
            if (messageList != null)
            {
                Text tt = new Text();
                tt.MessageWidth = calWidth(_messageList);
                tt.SenderID = 0;
                tt.TalkID = AppDomain.CurrentDomain.BaseDirectory + @"/Img/Header/头像6.png";
                tt.MessageType = NIMMessageType.kNIMMessageTypeText;              
                tt.TextContent = JsonConvert.SerializeObject(_messageList);
                messageList.Add(tt);

                MessageInfoList.Items.Refresh();
                MessageInfoList.ScrollIntoView(MessageInfoList.Items[MessageInfoList.Items.Count - 1]);
                richText_Send.Document.Blocks.Clear();//清空
            }
        }

        private string calWidth(List<ChatMessageRow> v)
        {

            double nMaxWidth = 0;
            double nWidth = 0;
            foreach (ChatMessageRow lc in v)
            {
                nWidth = 0;
                if (lc.rowType == "Paragraph")
                {                  
                    foreach (ChatMessage cm in lc.rowMessaget)
                    {
                        if (cm.messageType == 0)
                        {
                            nWidth += MeasureTextWidth(cm.text, 14, "Microsoft YaHei");
                        }
                        else if (cm.messageType == 1)
                        {
                            nWidth += Convert.ToDouble(cm.param1);
                        }
                    }

                    nMaxWidth = nMaxWidth < nWidth ? nWidth : nMaxWidth;
                }
                else if(lc.rowType == "BlockUIContainer")
                {

                    foreach (ChatMessage cm in lc.rowMessaget)
                    {
                        if (cm.messageType == 0)
                        {
                            nWidth += MeasureTextWidth(cm.text, 14, "Microsoft YaHei");
                        }
                        else if (cm.messageType == 1)
                        {
                            nWidth += Convert.ToDouble(cm.param1);
                        }
                    }

                    nMaxWidth = nMaxWidth < nWidth ? nWidth : nMaxWidth;

                }

            }

            nMaxWidth += 12;
            if (nMaxWidth > (MessageInfoList.ActualWidth - 120))
                nMaxWidth = MessageInfoList.ActualWidth - 120;

            return nMaxWidth.ToString();
        }

        private double MeasureTextWidth(string text, double fontSize, string fontFamily)
        {
            FormattedText formattedText = new FormattedText(
            text,
            System.Globalization.CultureInfo.InvariantCulture,
            FlowDirection.LeftToRight,
            new Typeface(fontFamily.ToString()),
            fontSize,
            System.Windows.Media.Brushes.Black
            );
            return formattedText.WidthIncludingTrailingWhitespace;
        }

        private void Button_Click_Cancel(object sender, RoutedEventArgs e)
        {
          
            var run = richText_Send.Selection.Start.Parent as Run;
            if(run != null)
            {
                string aba = run.Text;
            }
            var doc = this.richText_Send.Document;

            

            string adad = VisualTreeHelper.GetChild(this.richText_Send, 0).ToString();

            string bvbba = XamlWriter.Save(doc);

            var blocks = doc.Blocks.ToArray();
            // 判断一下是不是BlockUIContainer
            // 有可能里面不只一个BlockUIContainer
            var imgBlocks = blocks.Where(b => b is BlockUIContainer).ToArray();
            // 查看每一个BlockUIContainer的子元素，
            // 判断是不是Image类
            foreach (var item in imgBlocks)
            {
                BlockUIContainer uic = (BlockUIContainer)item;
                if (uic.Child is Image)
                {
                    Image imgCtl = uic.Child as Image;                 
                }
            }

            TextRange textRange = new TextRange(richText_Send.Document.ContentStart, richText_Send.Document.ContentEnd);
            string str =  textRange.Text;
            //AduMessageBox.Show("没问题，是你自己错误的！");
        }

        private void Button_Click_OpenImage(object sender, RoutedEventArgs e)
        {       
            string filepath = "";

           // string filename = "";

            System.Windows.Forms.OpenFileDialog openfilejpg = new System.Windows.Forms.OpenFileDialog();
            openfilejpg.Filter = "全部*.*|*.*|jpg图片(*.jpg)|*.jpg|png(*.png)|*.png|gif图片(*.gif)|*.gif";
            openfilejpg.FilterIndex = 0;
            openfilejpg.RestoreDirectory = true;
            openfilejpg.Multiselect = false;

            if (openfilejpg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                filepath = openfilejpg.FileName;

                Image img = new Image();

                BitmapImage bImg = new BitmapImage();

                img.IsEnabled = true;

                bImg.BeginInit();

                bImg.UriSource = new Uri(filepath, UriKind.Relative);

                bImg.EndInit();

                img.Source = bImg;

                //MessageBox.Show(bImg.Width.ToString() + "," + bImg.Height.ToString());

                /* 调整图片大小

                if (bImg.Height > 100 || bImg.Width > 100)

                {

                    img.Height = bImg.Height * 0.2;

                    img.Width = bImg.Width * 0.2;

                }*/

                img.Stretch = Stretch.None;  //图片缩放模式
                InlineUIContainer container = new InlineUIContainer(img);
                //Paragraph paragraph = new Paragraph(container);
                //richText_Send.Document.Blocks.Add(paragraph);

                TextPointer caretPos = richText_Send.CaretPosition;

                Run run = caretPos.Parent as Run;
                if (run != null)
                {
                    caretPos.Paragraph.Inlines.InsertAfter(run, container);
                }
                else
                {
                    caretPos.Paragraph.Inlines.Add(container);
                }

                //img.Stretch = Stretch.Uniform;  //图片缩放模式
                //new InlineUIContainer(img, richText_Send.Selection.Start); //插入图片到选定位置

            }

        }

        public List<ImageStruct> ImageList = new List<ImageStruct>();
        public List<ContentStruct> ContentList = new List<ContentStruct>();
    }
    public class ImageStruct
    {
        public System.Drawing.Point Img_Point;
        public int Img_Location;
        public Bitmap Img;

        public ImageStruct(System.Drawing.Point _point, int _location, Bitmap _img)
        {
            Img_Point = _point;
            Img_Location = _location;
            Img = _img;
        }
    }
  
    public class ContentStruct
    {
        public System.Drawing.Point Content_Point;
        public string Content_Text;

        public ContentStruct(System.Drawing.Point _point, string _text)
        {
            Content_Point = _point;
            Content_Text = _text;
        }
    }
   

    public class PersonNP : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; Notify(); }
        }

        private string id;
        public string Id
        {
            get { return id; }
            set { id = value; Notify(); }
        }

        // 属性值改变是通知，
        private void Notify([CallerMemberName]string obj = "")
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(obj));
            }
        }
    }

    public class PersonNP1 : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string image;
        public string Image
        {
            get { return image; }
            set { image = value; Notify(); }
        }

        private string text;
        public string Text
        {
            get { return text; }
            set { text = value; Notify(); }
        }

        private void Notify([CallerMemberName]string obj = "")
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(obj));
            }
        }
    }

    public class UserInfo
    {
        public string Image { get; set; }
        public string Name { get; set; }
        public string Info { get; set; }
        public int Count { get; set; }
    }

   

}
